/*
 * Copyright 2019-2029 geekidea(https://github.com/geekidea)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huibur.devicecheck.controller;


import com.huibur.devicecheck.model.entity.UploadResponse;
import com.huibur.devicecheck.request.ListRes;
import com.huibur.devicecheck.request.ObjRes;
import com.huibur.devicecheck.utils.DownloadUtil;
import com.huibur.devicecheck.utils.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 上传控制器
 *
 * @author geekidea
 * @date 2019/8/20
 * @since 1.2.1-RELEASE
 */
@Slf4j
@RestController
@RequestMapping("/files")
@Api(value = "文件操作", tags = {"文件操作"})
public class FileController {

    @Value("${upload-path}")
    private String uploadPath;
    @Value("#{'${allow-download-file-extensions}'.split(',')}")
    private List<String> allowFileExtensions;

    /**
     * 上传单个文件
     *
     * @return
     */
    @PostMapping
    @ApiOperation(value = "上传单个文件", response = ObjRes.class)
    public ObjRes<UploadResponse> upload(@ApiParam("文件") @RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws Exception {
        // 上传文件，返回保存的文件名称
        String saveFileName = UploadUtil.upload(uploadPath, multipartFile, (originalFilename, md5) -> {
            // 文件后缀
            String fileExtension = FilenameUtils.getExtension(originalFilename);
            return md5;
        });
        return new ObjRes<UploadResponse>().data(new UploadResponse("", saveFileName));
    }

    /**
     * 上传多个文件
     *
     * @return
     */
    @PostMapping("/uploadList")
    @ApiOperation(value = "上传多个文件", response = ListRes.class)
    public ListRes<UploadResponse> uploadList(@ApiParam("文件") @RequestParam("files") List<MultipartFile> multipartFiles, HttpServletRequest request) throws Exception {
        List<UploadResponse> uploadResponseList = new ArrayList<>();
        for (MultipartFile multipartFile : multipartFiles) {
            // 上传文件，返回保存的文件名称
            String saveFileName = UploadUtil.upload(uploadPath, multipartFile, (originalFilename, md5) -> {
                // 文件后缀
                String fileExtension = FilenameUtils.getExtension(originalFilename);
                return md5;
            });
            uploadResponseList.add(new UploadResponse("", saveFileName));
        }

        return new ListRes<UploadResponse>().data(uploadResponseList);
    }

    /**
     * 下载文件
     */
    @GetMapping("/{downloadFileName}")
    @ApiOperation(value = "下载文件", notes = "下载文件")
    public void download(@PathVariable(required = true) String downloadFileName, HttpServletResponse response) throws Exception {
        // 下载目录，既是上传目录
        String downloadDir = uploadPath;
        // 允许下载的文件后缀
       // List<String> allowFileExtensions = springBootPlusProperties.getAllowDownloadFileExtensions();

        // 文件下载，使用默认下载处理器
        // 文件下载，使用自定义下载处理器
        DownloadUtil.download(downloadDir, downloadFileName, allowFileExtensions, response,
                (dir, fileName, file, fileExtension, contentType, length) -> {
                    // 下载自定义处理，返回true：执行下载，false：取消下载
                    return true;
                });
    }
}
